#include"user_list.h"
#include<stdio.h>
#include<stdlib.h>

/*初始化头节点*/
User * user_init_list(void)
{
    User *user_head = malloc(sizeof(User));
    if(user_head!=NULL)
    {
        user_head->next = NULL;
    }
    return user_head;
}

/*创建新节点*/
User* user_new_node(Userinfo data)
{
    User * new =malloc(sizeof(User));
    if(new!=NULL){
        strcpy(new->username,data.username);
        strcpy(new->password,data.password);
        new->identity = data.identity;
        new->Total_consumption = data.Total_consumption;
        new->discount = data.discount;
        new->credits = data.credits;
        new->balance = data.balance;
        new->next = NULL;
    }
    return new;
}

/*判断链表是否为空*/
bool user_is_empty(User *list){
    return list->next==NULL;
}

/*插入节点*/
void user_insert_node(User * p,User * new)
{
    if(p==NULL || new ==NULL){
        return;
    }
    new->next=p->next;
    p->next=new;
}

/*删除节点*/
bool user_remove_node(User *mylist,User *delete)
{
    if(user_is_empty(mylist)){
        return false;
    }
    User * p=mylist;
    while(p!=NULL && p->next!=delete){
        p=p->next;
    }
    if(p==NULL){
        return false;
    }

    p->next=delete->next;
    delete->next=NULL;
    return true;
}

/*根据name查找节点*/
User* user_find_node_by_username(User* mylist,char *name)
{
    if(user_is_empty(mylist)){
        printf("empty\n");
        return NULL;
    }
    User* p;
    for(p=mylist->next;p!=NULL;p=p->next){
        if(strcmp(p->username,name) == 0){
            break;
        }
    }
    return p;
}

/*
** 功能：从文件加载数据
** filename		文件名字
*/ 
void user_file_load_data(User* head, const char *filename)
{
	FILE *fp = fopen(filename, "r");
	if(fp == NULL)
	{
		perror("file_load_data fail");
		return ;
	}
	// 从文件读取数据，加载到链表
	User tmp; 
	while(fread(&tmp, sizeof(User), 1, fp) == 1 )
	{
        Userinfo user= {
            .identity=tmp.identity,
            .Total_consumption = tmp.Total_consumption,
            .discount = tmp.discount,
            .credits = tmp.credits,
            .balance = tmp.balance
        };
        strcpy(user.username,tmp.username);
        strcpy(user.password,tmp.password);
		User *new = user_new_node(user);
		user_insert_node(head, new);
	}

	fclose(fp);
}

/*
** 功能：保存数据到文件
** filename		文件名字
*/ 
void user_file_save_data(User *head, const char *filename)
{
	FILE *fp = fopen(filename, "w");
	if(fp == NULL)
	{
		perror("file_save_data fail");
		return ;
	}
	
	// 把链表数据遍历，写入文件
	User *tmp = head->next;
	for( ; tmp != NULL; tmp = tmp->next)
	{
        printf("tmp->user=%s\n",tmp->username);

		int d = fwrite(tmp, sizeof(User), 1, fp);
        printf("d=%d\n",d);
	}	
	
	fclose(fp);
}